import {Component, OnInit,Output,EventEmitter, Input} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {CudTableService} from '../../public/serve/cud-table/cud-table.service';
import { internal } from '../../internal/internal.data';
import { InternalItems } from './internal.data';
import { appKeywordUrl } from '../../keyword/keyword.url';
import {HintsService} from '../../public/serve/hints/hints.service';
import { MatAutocompleteSelectedEvent } from '@angular/material';
import {Service} from '../../server/server';
import { ActivatedRoute, Params } from '@angular/router';
declare var $:any;
@Component({
    selector: 'app-internal-autocomplate',
    templateUrl: './internal-autocomplate.component.html',
    styleUrls: ['./internal-autocomplate.component.css'],
})

export class InternalAutocomplateComponent implements OnInit {
    myControl = new FormControl();
    @Output() inputComplete = new EventEmitter<void>();
    @Input() internalParam : any;
    public internalThemeWordsLeftEmit: any;
    options: any[] = [];
    filteredOptions: Observable<string[]>;
    public currentValue : any;
    currentThemeWordInfo : object;
    taskType:any;

    constructor(
        public request: CudTableService,
        private hintsService: HintsService,
        private server: Service,
        private activatedRoute: ActivatedRoute,
    ) { }

    ngOnInit() {
        this.activatedRoute.queryParams.subscribe((p: Params) => {
            this.taskType = p['taskType'];
        });
        this.myControl.valueChanges.subscribe(data=>{
            this.currentValue = null;
            this._filter();
        });
        //internalThemeWordsLeftEmit
        this.internalThemeWordsLeftEmit = this.server.internalThemeWordsLeftEmit.subscribe((value: any) => {
            if (value) {
                this.currentThemeWordInfo = value
            }
        });
    }

    ngOnDestroy() {
        this.internalThemeWordsLeftEmit ? this.internalThemeWordsLeftEmit.unsubscribe() : '';
    }

    _filter(){
        let tmpValue = this.myControl.value;
        let filterValue = '';
        if(tmpValue != ''&& Object.prototype.toString.call(tmpValue) !== '[object Object]'){
            if(Object.prototype.toString.call(tmpValue) === '[object Object]'){
                filterValue = tmpValue['txt'];
            }else{
                filterValue = tmpValue;
            }

            if(this.taskType == 2){
                this.getThemeWordsByIndex(filterValue);
            }else{
                let data = this._tableData();
                data.queryCriteria = filterValue;
                this.request.postRequest(this.server.baseUrl +appKeywordUrl.getThemeWordsList,data).then((res:any) => {
                    this.options = [];
                    if (res.result_code === '0000') {
                        res.result.forEach((item, index)=>{
                            this.options.push({
                                'txt':item.name,
                                'val':item.themeWordsId
                            });
                        });
                    }else{
                        this.hintsService.messages(res.message,res.result_code);
                    }
                })
                    .catch((err: any)=>{
                        this.hintsService.messages("error","error");
                    });
            }
        }else{
            this.options = [];
        }
    }

    //查询参数
    private _tableData(){
        return {
            token         : internal.retrieval.token,
            pageNo        : internal.pagination.pageNo,
            pageSize      : internal.pagination.pageSize,
            status        : internal.retrieval.status,
            themeCode     : internal.retrieval.themeCode,
            checkStatus   : internal.retrieval.checkStatus,
            startTime     : internal.retrieval.startTime,
            endTime       : internal.retrieval.endTime,
            queryCriteria : internal.retrieval.queryCriteria,
            themeTableId  : this.internalParam.themeTableId,
        }
    }

    //回车事件
    _selectValue(){
        if(Object.prototype.toString.call(this.currentValue) === '[object Object]'){
            //标引主题词
            //this.inputComplete.emit(this.currentValue);
        }else if(this.internalParam.checkStatusData != 200){
            //不存在的主题词或未空的主题词
            this.hintsService.messages('请输入已有的主题词名称','9999');
        }
    }   

    onSelectionChanged(event: MatAutocompleteSelectedEvent) {
        if(this.internalParam.completeStatus != '1' && this.internalParam.checkStatusData != 200){
            
            this.currentValue = event['value'];
            this.inputComplete.emit(this.currentValue);
        }else if(this.internalParam.checkStatusData == 200 && this.internalParam.completeStatus != '1'){
                this.hintsService.messages('该产品已完成审核，不能再标引！','9999');
        }else if(this.internalParam.completeStatus == '1' && this.internalParam.statusData == 1){
            this.hintsService.messages('该任务已结案，不能再标引！','9999');
        }
        
    }

    displayFn(items: InternalItems): any {
        return items ? items.txt : items;
    }

    //获取未标引主题词信息
    getThemeWordsByIndex(filterValue){
        if(this.currentThemeWordInfo){
            let data = {
                pageNo        : 1,
                pageSize      : 999,
                themeWordsName : filterValue,
                themeTableId  :  this.currentThemeWordInfo['themeTableId'], // 左侧主题词表id
                themeWordsId  :  this.currentThemeWordInfo['themeWordsId'],    //左侧主题词id
                productId  : this.internalParam['productId'],
                taskId  : this.internalParam['taskId'],
                relThemeTableId  :this.internalParam['themeTableId'],    //当期主题词表id
            };
            let url = this.server.baseUrl +  'Service/IdxProduct/getNoRelationThemeList';
            this.request.postRequest(url,data).then((res:any) => {
                this.options = [];
                if (res.result_code === '0000') {
                    res.result.forEach((item, index)=>{
                        this.options.push({
                            'txt':item.name,
                            'val':item.themeWordsId
                        });
                    });
                }else{
                    this.hintsService.messages(res.message,res.result_code);
                }
            })
                .catch((err: any)=>{
                    this.hintsService.messages("error","error");
                    return;
                });

        }else{
            this.hintsService.messages('请先选中左侧主题词','9999');
        }

    }



}